
#include <stdio.h>
#include <string.h> 
#include <stdlib.h>


#include "TLVUtil.h"

#define		SIZE_OF_UNSIGNEDINT			4
#define		SIZE_OF_UNSIGNEDCHAR		1

void  put_32(unsigned  char   *cmd, unsigned  int  data)
{
	int  i;
	for  (i  =  SIZE_OF_UNSIGNEDINT  -   1 ; i  >=   0 ;  -- i)
	{
		cmd[i]  =  data  %   256 ;
		/* cmd[i] = data & 0xFF; */
		data  =  data  >>   8 ;
	} 
} 

unsigned  int  get_32(unsigned  char   *cmd)
{
	unsigned  int   ret;
	int  i;
	for  (ret  =   0 , i  =  SIZE_OF_UNSIGNEDINT  -   1 ; i  >=   0 ;  -- i)
	{
		ret   =  ret  <<   8 ;
		ret  |=  cmd[i];        
	}     
	return  ret;
} 

unsigned char calc_lrc(unsigned char origin, unsigned char const* data, int length)
{
    int i;
	unsigned char lrc = origin;

	if (NULL == data || length < 0)
		return 0x00;

	for (i = 0; i < length; i++)
	{
		lrc ^= data[i];
	}

	return lrc;
}

void _vdStr2HexStr(char const *i_szAsc, unsigned char *ppbt_Byte, int *iByteLength)
{
	int iLength = *iByteLength;	
	int iPos	= 0;
	int iLeft;
	int iRight;
	int iIndex;


	for (iIndex = 0; iIndex < iLength; iIndex++, iPos++) 
	{
		iLeft = i_szAsc[iIndex++];
		iRight = i_szAsc[iIndex];

		iLeft = (iLeft < 58) ? (iLeft - 48) : (iLeft - 55);
		iRight = (iRight < 58) ? (iRight - 48) : (iRight - 55);

		ppbt_Byte[iPos] = ((iLeft << 4) | iRight)& 0xff;
	}

	*iByteLength = iPos;

	return;
}

void _Int2Byte(int i_Int, unsigned char *us_Byte)
{
	unsigned int ui_Output;
	unsigned char szTemp[2];
	
	ui_Output = (unsigned int) i_Int;

	szTemp[1] = ui_Output;
	szTemp[0] = ui_Output >>8;

	memcpy(us_Byte, szTemp, 2);
}

void _vdHex2Str (char const  *pstHex, int inLen, char *pstStr)
{
	int inCnt;
	char pstTemp[3];

	memset( pstTemp, 0, sizeof(pstTemp) );

	*pstStr = 0;
	
	for(inCnt=0; inCnt<inLen; inCnt++)
	{
		sprintf(pstTemp, "%02X", pstHex[inCnt]);
		strcat((char *)pstStr, pstTemp);
	}
	
	return;
}

void _vdHex2String (unsigned char *pstHex, int inLen, char *pstStr)
{
	int inCnt;
	char pstTemp[3];

	memset( pstTemp, 0, sizeof(pstTemp) );

	for(inCnt=0; inCnt<inLen; inCnt++)
	{
		sprintf(pstTemp, "%02X", pstHex[inCnt]);
		strcat(pstStr, pstTemp);
	}
	
	return;
}

void _ByteToInt(unsigned char const* usz_In, int i_length, int *i_pOut)
{
	int iCount = 0;
	*i_pOut = 0;
 
	for (iCount = 0; iCount < i_length; iCount++)
	{
		*i_pOut += usz_In[iCount];
		if (iCount < i_length - 1) *i_pOut = *i_pOut << 8;
	}

}

unsigned int _HTONL_(unsigned int h)
{
	unsigned char	acCmd[4];
	unsigned int	iTmp = 0;

	memset(acCmd, 0, sizeof(acCmd));
	put_32(acCmd, h);

	memcpy(&iTmp, acCmd, 4);

	return iTmp;
}

unsigned int _NTOHL_(unsigned int h)   
{   
	//return (h<<24) + ((h<<16)>>8) + ((h<<8)>>16) + (h>>24);

	return _HTONL_(h);
}


unsigned short _HTONS_(unsigned short h)   
{   
	return (h>>8) + (h<<8);
}

int is_big_endian(void)
  {
     long one = 1;
     return !(*((char *)(&one)));
  }
